﻿extern alias oldTweetSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;

namespace Social_Celebrities
{
    public partial class TwitterLoginPage : PhoneApplicationPage
    {
        oldTweetSharp::TweetSharp.TwitterService service;
        private const string consumerKey = "LYTy3T8P556GxqRymimhwA";
        private const string consumerSecret = "5TSKipEjESOAcdBsViWm2E1RVxFEN1Ooh0nRwIj7RsY";
        private oldTweetSharp::TweetSharp.OAuthRequestToken requestToken;
        private oldTweetSharp::TweetSharp.OAuthAccessToken accesToken;
        private bool userAuthenticated = false;
        public TwitterLoginPage()
        {
            InitializeComponent();
            Loaded += TwitterLoginPage_Loaded;
           
        }
        void TwitterLoginPage_Loaded(object sender, RoutedEventArgs e)
        {
           if(NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("AddAccount.xaml"))
           NavigationService.RemoveBackEntry();
            service = new oldTweetSharp::TweetSharp.TwitterService(consumerKey, consumerSecret);
            service.GetRequestToken((processRequestToken));
        }

        private void processRequestToken(oldTweetSharp::TweetSharp.OAuthRequestToken token, oldTweetSharp::TweetSharp.TwitterResponse response)
        {
            if (token == null)
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Request token"); });
            else
            {
                requestToken = token;
                Dispatcher.BeginInvoke(() =>
                {
                    var ghh = service.GetAuthorizationUri(requestToken);
                    Browser.Navigate(service.GetAuthorizationUri(requestToken));
                });
            }
        }

        private void processAccessToken(oldTweetSharp::TweetSharp.OAuthAccessToken token, oldTweetSharp::TweetSharp.TwitterResponse response)
        {
            if (token == null)
            {
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Access token"); });
                  Dispatcher.BeginInvoke(() =>
                {
                NavigationService.GoBack();
                });
            }
            else
            {
                accesToken = token;
                service.AuthenticateWith(token.Token, token.TokenSecret);
                saveAccessToken(token);
                 Dispatcher.BeginInvoke(() =>
                {
                NavigationService.GoBack();
                });
            }
        }

        private void saveAccessToken(oldTweetSharp::TweetSharp.OAuthAccessToken token)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken"))
                IsolatedStorageSettings.ApplicationSettings["accessToken"] = token;
            else
                IsolatedStorageSettings.ApplicationSettings.Add("accessToken", token);

            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        public oldTweetSharp::TweetSharp.OAuthAccessToken getAccessToken()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken"))
                return IsolatedStorageSettings.ApplicationSettings["accessToken"] as oldTweetSharp::TweetSharp.OAuthAccessToken;
            else
                return null;
        }


        public static IDictionary<string, string> ParseQueryString(string query)
        {

            if (query.StartsWith("?")) query = query.Substring(1);

            if (query.Equals(string.Empty))
            {
                return new Dictionary<string, string>();
            }

            var parts = query.Split(new[] { '&' });

            return parts.Select(
                part => part.Split(new[] { '=' })).ToDictionary(
                    pair => pair[0], pair => pair[1]
                );
        }

        private void BrowserNavitaged(object sender, NavigationEventArgs e)
        {
            if (e.Uri.AbsoluteUri.Contains("oauth_verifier"))
            {
                var values = ParseQueryString(e.Uri.AbsoluteUri);
                string verifier = values["oauth_verifier"];
                service.GetAccessToken(requestToken, verifier, processAccessToken);
            }
        }
        public string[] ReturnTokens(oldTweetSharp::TweetSharp.OAuthAccessToken Token)
        {
            string [] Tokens=new string[2];
            if (Token != null)
            {
                Tokens[0] = Token.Token;
                Tokens[1] = Token.TokenSecret;
            }
            return Tokens;
        }
    }
}